# coding: utf-8

from datetime import datetime
import xml.sax

from flask import request, jsonify

from .. import db
from . import xunke_bp
from .models import BaiduXunkeRecord
from .utils import XMLHandler
from app.op.constant import UserType, DemandSource, DemandClientSource
from app.op.models import User, Demand, Area, DemandClient
from app.ccws.models import create_outbound_mission
from app.ccws.constant import CallReason


@xunke_bp.route('/test', methods=['GET'])
def test():
    return 'hello xunke'


@xunke_bp.route('/push_message', methods=['POST'])
def push_message():
    """
    百度寻客推送消息接口
    """
    data = request.data
    xml_handler = XMLHandler()
    xml.sax.parseString(data, xml_handler)
    ret = xml_handler.get_dict()

    kwargs = {
        'user_name': ret.get('userName', ''),
        'password': ret.get('password', ''),
        'target_url': ret.get('OptimizationURL', ''),
        'query_word': ret.get('Query', ''),
        'query_time': ret.get('queryTime', ''),
        'device': ret.get('Device', ''),
        'user_id': ret.get('baiduUserid', ''),
        'city_code': ret.get('cityCode', ''),
        'city_name': ret.get('cityName', ''),
        'plan_id': ret.get('planId', ''),
        'unit_id': ret.get('unitId', ''),
        'winfo_id': ret.get('winfoId', ''),
        'name': ret.get('name', ''),
        'company_name': ret.get('companyName', ''),
        'email': ret.get('email', ''),
        'mobile': ret.get('mobile', ''),
    }
    xunke_record = BaiduXunkeRecord.create(**kwargs)

    # 新建用户与项目
    nickname = kwargs['name'] or '百度寻客客户'
    mobile = kwargs['mobile']
    user = User.get_by_args(mobile=mobile, deleted_at=0)
    city = Area.query.filter_by(name=kwargs['city_name']).first()
    prov = Area.query.filter_by(id=city.pid).first() if city else None

    if not user:
        user = User.create(
            mobile=mobile,
            nickname=nickname,
            area_id=city.id if city else 0,
            prov=prov.name if prov else '',
            city=city.name if city else '',
            type=UserType.CLIENT.value
        )
    # 创建需求
    demand = Demand.create(
        uid=user.id,
        area_id=city.id if city else 0,
        source=DemandSource.BAIDU.value,
    )
    # NOTE by chenhj 百度寻客只有A组有(超哥说百度寻客已经不允许新申请了, 所以只有A组有)
    DemandClient.visit(
        user.id, DemandClientSource.BAIDU_XUNKE.value, sem_path='A-寻客'
    )
    # 百度寻客增加外呼任务
    tmp_outbound_record, err = create_outbound_mission(
        mobile=user.mobile,
        call_reason=CallReason.XUNKE_CALLBACK.value,
        schedule_time=datetime.now(),
        user_id=user.id
    )
    if tmp_outbound_record:
        db.session.add(tmp_outbound_record)

    response = {
        'message': 'succesed',
    }
    return jsonify(response)

